import React, { useState, useEffect, useRef } from 'react'
import './index.modules.scss'
import SearchView from '@/components/searchView/index'
import { baseURL } from '@/http/request'
import { useLocation, useNavigate } from 'react-router-dom'
import {
  Space,
  Table,
  Button,
  Modal,
  Card,
  message,
  Input,
  Popconfirm,
  Pagination,
  Image,
  Divider,
  Form,
  Select,
  DatePicker,
  Upload
} from 'antd'
import {
  LeftOutlined,
  FolderAddOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons'
import {
  storeQualityList,
  storeQualitySerach,
  storeQualityCreateExcel,
  storeQualityChange,
  storeQualityDelete
} from '@/http/api/store'
import dayjs from 'dayjs'
let pageData = {
  page: 1,
  size: 10,
  total: 0,
  appid: localStorage.getItem('appid')
}
const { RangePicker } = DatePicker
const { TextArea } = Input
let _id = ''
let typeList = [
  {
    title: '车主名称',
    type: 'inpute',
    model: 'ownerName'
  },
  {
    title: '联系方式',
    type: 'inpute',
    model: 'ownerPhone'
  },
  {
    title: '质保编号',
    type: 'inpute',
    model: 'filmNo'
  },
  {
    title: '车架号',
    type: 'inpute',
    model: 'carVIN'
  },
  {
    title: '施工时间',
    type: 'date',
    model: 'workTime'
  },
  {
    title: '产品型号',
    type: 'inpute',
    model: 'filmType'
  },
  {
    title: '车辆型号',
    type: 'inpute',
    model: 'carName'
  }
]

let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]

let optionsFilmName = [
  { value: 'DS13S', label: 'DS13S' },
  { value: 'DS14S', label: 'DS14S' },
  { value: 'QS13S', label: 'QS13S' }
]

let optionsCarApart = [
  { value: '整车', label: '整车' },
  { value: '前挡', label: '前挡' },
  { value: '侧挡', label: '侧挡' },
  { value: '车顶', label: '车顶' },
  { value: '前杠', label: '前杠' },
  { value: '后杠', label: '后杠' },
  { value: '机盖', label: '机盖' },
  { value: '前叶子板', label: '前叶子板' },
  { value: '后叶子板', label: '后叶子板' },
  { value: '车门', label: '车门' },
  { value: '侧裙', label: '侧裙' },
  { value: '后盖', label: '后盖' }
]
let selectedRowsdata = []
const App = () => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const Navigate = useNavigate()
  const location = useLocation()
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, setIsShowAdd] = useState(false)
  const [isShowDetils, setisShowDetils] = useState(false)
  const [isImgShow, setIsImgShow] = useState(false)
  const [detilsData, setDetilsData] = useState({})
  const [magnifyImg, setMagnifyImg] = useState('')
  const [upImgList, setUpImgList] = useState([
    {
      title: '车辆与门头照片'
    },
    {
      title: '施工车辆照片'
    },
    {
      title: '膜卷号'
    },
    {
      title: '车辆铭牌照片'
    }
  ])

  const columns = [
    {
      title: '质保上传时间',
      dataIndex: 'workTime',
      align: 'center'
    },
    {
      title: '产品类型',
      dataIndex: 'filmType',
      align: 'center'
    },
    {
      title: '产品名称',
      dataIndex: 'filmName',
      align: 'center'
    },
    {
      title: '施工门店',
      dataIndex: 'storeWorkName',
      align: 'center'
    },
    {
      title: '车主姓名',
      dataIndex: 'ownerName',
      align: 'center'
    },
    {
      title: '联系方式',
      dataIndex: 'ownerPhone',
      align: 'center'
    },
    {
      title: '车牌号',
      dataIndex: 'carNo',
      align: 'center'
    },
    {
      title: '车架号',
      dataIndex: 'carVIN',
      align: 'center'
    },
    {
      title: '施工部位',
      dataIndex: 'carApart',
      align: 'center'
    },
    {
      title: '质保年限',
      dataIndex: 'filmAge',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            onClick={() => {
              setisShowDetils(true)
              data.timeOfReceipt = dayjs(data.timeOfReceipt)
              data.imgList = Array.isArray(data.imgList)
                ? data.imgList
                : JSON.parse(data.imgList)
              setDetilsData(data)
            }}
          >
            详情
          </Button>
          <Button
            type="primary"
            onClick={() => {
              let changeData = {}
              changeData = JSON.parse(JSON.stringify(data))
              _id = data._id
              changeData.imgList = Array.isArray(changeData.imgList)
                ? changeData.imgList
                : JSON.parse(changeData.imgList)
              setUpImgList(
                Array.isArray(data.imgList)
                  ? data.imgList
                  : JSON.parse(data.imgList)
              )
              setDetilsData(changeData)
              form.setFieldsValue(changeData)
              setIsShowAdd(true)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }

  // 获取列表
  const getList = async () => {
    pageData.storeId = location.state.id
    const res = await storeQualityList(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id,
          workTime: dayjs(item.workTime).format('YYYY-MM-DD HH:mm:ss')
        }
      })
    )
    pageData.total = res.data.total
  }
  // 点击确定修改
  const onFinish = async (data) => {
    data.imgList = upImgList
    let upData = detilsData

    data._id = detilsData._id
    console.log(data)
    // for (const key in detilsData) {
    //   for (const key2 in data) {
    //     if (key == key2) {
    //       upData[key] = data[key2]
    //     }
    //   }
    // }
    const res = await storeQualityChange(data)
    setIsShowAdd(false)
    messageApi.success(res.data.message)
    getList()
  }
  const showModalAdd = (value) => {
    if (value._id) {
      setDetilsData(value)
      _id = value._id
    }
    setIsShowAdd(true)
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await storeQualityDelete({ id: data._id })
    messageApi.success(res.data.messge)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {}
    if (selectedRowsdata.length == 0) {
      data = {
        id: 'all',
        storeId: location.state.id
      }
    } else {
      data = {
        id: selectedRowsdata,
        storeId: location.state.id
      }
    }
    const res = await storeQualityCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '质保.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  // 搜索
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      storeId: location.state.id,
      ...data
    }
    const res = await storeQualitySerach(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id,
          workTime: dayjs(item.workTime).format('YYYY-MM-DD HH:mm:ss')
        }
      })
    )
    pageData.total = res.data.total
  }
  // 删除照片
  const deleteImgFn = (index) => {
    let allDataList = upImgList
    allDataList[index].img = ''
    setUpImgList([...allDataList])
  }
  const fileChange = async (index, data) => {
    if (data.file.status == 'done') {
      let allDataList = upImgList
      allDataList[index].img = data.fileList[0].response.image_url
      setUpImgList([...allDataList])
    }
    console.log(upImgList)
  }
  return (
    <div>
      <Card>
        <div className="headerTitle align_center">
          <LeftOutlined
            onClick={() => {
              Navigate(-1)
            }}
            style={{ fontSize: '50px' }}
          ></LeftOutlined>
          <div>门店名称：{location.state.name}</div>
        </div>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="headerButton">
          <div>
            <Button
              type="primary"
              onClick={() => {
                exportExcel()
              }}
            >
              导出信息
            </Button>
          </div>
        </div>
        <Table
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
          pagination={false}
          bordered
          rowKey="key"
          columns={columns}
          dataSource={dataSource}
        />
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      {/* 修改 */}
      <div>
        <Modal
          footer={[]}
          onCancel={() => {
            setIsShowAdd(false)
          }}
          open={isShowAdd}
        >
          <div className="addCardBox">
            <div className="addCard" style={{ minHeight: '240px' }}>
              <div className="addCardTitle">质保信息</div>
              <Form
                form={form}
                name="basic"
                labelCol={{
                  span: 6
                }}
                wrapperCol={{
                  span: 16
                }}
                style={{
                  maxWidth: 600
                }}
                initialValues={detilsData}
                onFinish={onFinish}
                autoComplete="off"
              >
                <Form.Item
                  label="产品类型："
                  name="filmType"
                  rules={[
                    {
                      required: true,
                      message: '请输入产品类型'
                    }
                  ]}
                >
                  <Select className="inputeStyle" options={optionsFilmType} />
                </Form.Item>
                <Form.Item
                  label="产品名称："
                  name="filmName"
                  rules={[
                    {
                      required: true,
                      message: '请输入产品名称'
                    }
                  ]}
                >
                  <Select className="inputeStyle" options={optionsFilmName} />
                </Form.Item>
                <Form.Item
                  label="质保编号："
                  name="filmNo"
                  rules={[
                    {
                      required: true,
                      message: '请输入质保编号'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
                <Form.Item
                  label="质保年限："
                  name="filmAge"
                  rules={[
                    {
                      required: true,
                      message: '请输入质保年限'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>

                <Form.Item label="备注：" name="remark">
                  <TextArea className="inputeStyle" />
                </Form.Item>
              </Form>
            </div>
            <div className="addCard" style={{ minHeight: '80px' }}>
              <div className="addCardTitle">门店信息</div>
              <Form
                form={form}
                name="basic"
                labelCol={{
                  span: 6
                }}
                wrapperCol={{
                  span: 16
                }}
                style={{
                  maxWidth: 600
                }}
                initialValues={detilsData}
                onFinish={onFinish}
                autoComplete="off"
              >
                <Form.Item
                  label="施工门店："
                  name="storeWorkName"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" disabled />
                </Form.Item>
              </Form>
            </div>
            <div className="addCard" style={{ minHeight: '100px' }}>
              <div className="addCardTitle">车主信息</div>
              <Form
                form={form}
                name="basic"
                labelCol={{
                  span: 6
                }}
                wrapperCol={{
                  span: 16
                }}
                style={{
                  maxWidth: 600
                }}
                initialValues={detilsData}
                onFinish={onFinish}
                autoComplete="off"
              >
                <Form.Item
                  label="姓名："
                  name="ownerName"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
                <Form.Item
                  label="电话："
                  name="ownerPhone"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
              </Form>
            </div>
            <div className="addCard" style={{ minHeight: '160px' }}>
              <div className="addCardTitle">车辆信息</div>
              <Form
                name="basic"
                labelCol={{
                  span: 6
                }}
                wrapperCol={{
                  span: 16
                }}
                style={{
                  maxWidth: 600
                }}
                initialValues={detilsData}
                onFinish={onFinish}
                autoComplete="off"
                form={form}
              >
                <Form.Item
                  label="品牌型号："
                  name="carName"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
                <Form.Item
                  label="车牌号："
                  name="carNo"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
                <Form.Item
                  label="车架号："
                  name="carVIN"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Input className="inputeStyle" />
                </Form.Item>
                <Form.Item
                  label="施工部位："
                  name="carApart"
                  rules={[
                    {
                      required: true,
                      message: '请输入'
                    }
                  ]}
                >
                  <Select className="inputeStyle" options={optionsCarApart} />
                </Form.Item>
              </Form>
            </div>
            <div className="addCard imgCard" style={{ minHeight: '380px' }}>
              {upImgList.map((item, index) => {
                if (item.img) {
                  return (
                    <div key={index} className="upImgBox">
                      <div className="imgTitle">{item.title}</div>
                      <div className="imgBox center">
                        <img
                          style={{ width: '100%', height: '100%' }}
                          src={item.img}
                          alt=""
                        />
                        <div
                          className="mask center"
                          style={{ justifyContent: 'space-evenly' }}
                        >
                          <DeleteOutlined
                            onClick={() => {
                              deleteImgFn(index)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                          <EyeOutlined
                            onClick={() => {
                              setMagnifyImg(item.img)
                              setIsImgShow(true)
                            }}
                            style={{ fontSize: 20, color: '#FFFFFF' }}
                          />
                        </div>
                      </div>
                    </div>
                  )
                } else {
                  return (
                    <div key={index} className="upImgBox">
                      <div className="imgTitle">{item.title}</div>
                      <div className="imgBox center">
                        <Upload
                          maxCount={1}
                          action={baseURL + 'api/uploadAvatar'}
                          onChange={(data) => {
                            fileChange(index, data)
                          }}
                        >
                          <FolderAddOutlined style={{ fontSize: '120px' }} />
                        </Upload>
                      </div>
                    </div>
                  )
                }
              })}
            </div>
            <Form form={form} onFinish={onFinish}>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
      <Modal
        title="详情"
        open={isShowDetils}
        footer={[]}
        onCancel={() => {
          setisShowDetils(false)
        }}
      >
        <div className="detilsBox">
          <div
            className="card"
            style={{ width: '369px', height: '191px', padding: '15px' }}
          >
            <div className="cardtitle">产品信息</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitle">产品类型：</div>
                <div className="ContentSize">{detilsData.filmType}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">产品型号：</div>
                <div className="ContentSize">{detilsData.filmName}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">质保年限：</div>
                <div className="ContentSize">{detilsData.filmAge}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">质保时间：</div>
                <div className="ContentSize">{detilsData.workTime}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">质保编号：</div>
                <div className="ContentSize">{detilsData.filmNo}</div>
              </div>
            </div>
          </div>
          <div
            className="card"
            style={{ width: '369px', minHeight: '80px', padding: '15px' }}
          >
            <div className="cardtitle">门店信息</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitle">施工门店：</div>
                <div className="ContentSize">{detilsData.storeWorkName}</div>
              </div>
            </div>
          </div>
          <div
            className="card"
            style={{ width: '369px', minHeight: '102px', padding: '15px' }}
          >
            <div className="cardtitle">车主信息</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitle">姓名：</div>
                <div className="ContentSize">{detilsData.ownerName}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">电话：</div>
                <div className="ContentSize">{detilsData.ownerPhone}</div>
              </div>
            </div>
          </div>
          <div
            className="card"
            style={{ width: '369px', minHeight: '166px', padding: '15px' }}
          >
            <div className="cardtitle">车辆信息</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitle">品牌型号：</div>
                <div className="ContentSize">{detilsData.carName}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">车牌号：</div>
                <div className="ContentSize">{detilsData.carNo}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">车架号：</div>
                <div className="ContentSize">{detilsData.carVIN}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">施工部位：</div>
                <div className="ContentSize">{detilsData.carApart}</div>
              </div>
            </div>
          </div>
          <div
            className="card"
            style={{ width: '369px', minHeight: '110px', padding: '15px' }}
          >
            <div className="cardtitle">车衣险电子保单</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitlelink">
                  未查询到香港车衣保险单，您可以点击此处，
                </div>
                <div
                  className="ContentSizelink"
                  onClick={() => {
                    Navigate('/home/carOwnerInsurance', {
                      state: {
                        id: detilsData.carOwnerId,
                        name: detilsData.ownerName,
                        phone: detilsData.ownerPhone
                      }
                    })
                  }}
                >
                  前往查询
                </div>
              </div>
            </div>
          </div>
          <div
            className="card"
            style={{ width: '369px', minHeight: '400px', padding: '15px' }}
          >
            <div className="imgCardBox">
              {detilsData.imgList
                ? detilsData?.imgList.map((item) => {
                    return (
                      <div className="imgCard">
                        <div className="imgTitle">{item.title}</div>
                        <div>
                          <Image width={130} height={130} src={item.img} />
                        </div>
                      </div>
                    )
                  })
                : ''}
            </div>
          </div>
        </div>
        <div className="center">
          <div
            className="footButton center"
            onClick={() => {
              setisShowDetils(false)
            }}
          >
            确定
          </div>
        </div>
      </Modal>

      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={magnifyImg} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
}
export default App
